package group32.client;

import group32.shared.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dev.asm.commons.AdviceAdapter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.user.datepicker.client.DatePicker;


public class EditProfile extends Composite {
	int userid=-1;
	private EditProfileServiceAsync pService = GWT
	.create(EditProfileService.class);
	
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	
	
		private VerticalPanel mainPanel = new VerticalPanel();
		private VerticalPanel dummy = new VerticalPanel();
		FormPanel editForm =new FormPanel();
		private VerticalPanel outer = new VerticalPanel();
		private VerticalPanel contentPanel = new VerticalPanel();
		  private HorizontalPanel addPanel = new HorizontalPanel();
		  private ListBox faculty = new ListBox();
		  final Label notifyLabel = new Label();
		  final TextBox titleLabel = new TextBox();
		  final Label errorLabel = new Label();
			final Button sendButton = new Button("Save");
			final Button resetButton = new Button("Cancel");
			final TextBox nameField = new TextBox();
			final TextBox firstName = new TextBox();
			final TextBox school = new TextBox();
			final TextBox major = new TextBox();
			final TextBox yearsAd = new TextBox();
			final TextBox rmNumber = new TextBox();
			final DateBox dob = new DateBox();
			final ListBox gender = new ListBox();
			final ListBox advisor = new ListBox();
			final TextBox lastName = new TextBox();
			final TextArea interests = new TextArea();
			final TextArea address = new TextArea();
			final TextArea research = new TextArea();
			final TextBox email = new TextBox();
			final TextBox gpa = new TextBox();
			final TextBox year = new TextBox();
		  User curUser=new User();
		/**
		 * This is the entry point method.
		 */
		public EditProfile(final String userType,final int uid,final String username) {
			
			History.newItem("edituser");		
			editForm.addStyleName("table-center");

			Window.setTitle("Edit Profile Details");	
			
			dummy.setHeight("20px");
			mainPanel.add(dummy);
			sendButton.addStyleName("sendButton");
			addPanel.add(sendButton);
			addPanel.add(resetButton);

			 gender.addItem("Male", "M");
			 gender.addItem("Female", "F");
			getUserDetails(uid,userType);
			// We can add style names to widgets
			

			initWidget(outer);
			// Add a handler to add a user
			sendButton.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					curUser.firstname=firstName.getText();
					curUser.lastname=lastName.getText();
					curUser.address=address.getText();
					curUser.dob=dob.getValue();
					curUser.email=email.getText();
					curUser.gender=gender.getItemText(gender.getSelectedIndex()).charAt(0);
					curUser.address=address.getText();
					curUser.school=school.getText();
					curUser.interests=interests.getText();
					if(userType.equals("S")){
					curUser.major=major.getText();
					curUser.year= Integer.parseInt(year.getText());
					curUser.GPA=Double.parseDouble(gpa.getText());
					curUser.advises=Integer.parseInt(faculty.getValue(faculty.getSelectedIndex()));
					curUser.yearsAdvised=Integer.parseInt(yearsAd.getText());
					}
					if(userType.equals("P")){
						curUser.title=titleLabel.getText();
						curUser.roomNumber= Integer.parseInt(rmNumber.getText());
						curUser.researchArea=research.getText();
						}
					updateUser(uid,curUser,userType,username);
				}
			
			});

			sendButton.addKeyPressHandler(new KeyPressHandler() {
				
				@Override
				public void onKeyPress(KeyPressEvent event) {
					 if (event.getCharCode() == KeyCodes.KEY_ENTER) {
						
				        }
					
				}
			});
		
			resetButton.addClickHandler(new ClickHandler(){
				public void onClick(ClickEvent event) {
				FlowControl.go(new UserProfile(uid,userType, 0, username,1));
				}
			});

			  
		}
	
		
		public String greetServer(String name) throws IllegalArgumentException {
			// TODO Auto-generated method stub
			return null;
		}
		  /**
		   * Add user to the db. Executed when the user clicks the register button or
		   * presses enter.
		   */
		  public void getAdvisors()
				  throws IllegalArgumentException {
		  
		    // TODO Auto-generated method stub
	          pService.getFaculty(new AsyncCallback<ArrayList<User>>(){
					public void onSuccess(ArrayList<User> result) {
						try {
							if(result!=null){
								int c=0;
								for (User u : result) {
									String s=u.firstname+" "+u.lastname;
									String id=Integer.toString(u.userID);
									System.out.println(s+""+c);
								faculty.insertItem(s,id,c);
								c++;
								}
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	                  }
	                  
	                  public void onFailure(Throwable caught) {
	                	  faculty.addItem("No faculty in DB");
	  					//mainPanel.add(faculty);
	                  }            
	                  
	          });
		  }

		  public void getUserDetails(int uid,final String utype)
				  throws IllegalArgumentException {
		  System.out.println(uid);
		    // TODO Auto-generated method stub
	          pService.getUser(uid,utype,new AsyncCallback<User>(){
					public void onSuccess(User result) {
						curUser=result; 
						mainPanel.add(new Label("Username:"));
						nameField.setText(curUser.username);
						 nameField.setEnabled(false);
						 mainPanel.add(nameField);
						if(utype.equals("P")){
							mainPanel.add(new Label("Title:"));
							if(curUser.title!=null)
								 titleLabel.setText(curUser.title);
								 mainPanel.add(titleLabel);
							}
						mainPanel.add(new Label("Firstname:"));
						 firstName.setText(curUser.firstname);
							firstName.setFocus(true);
							firstName.selectAll();
							mainPanel.add(firstName);
							mainPanel.add(new Label("Lastname:"));
						 lastName.setText(curUser.lastname);
						 mainPanel.add(lastName);
						 
						 mainPanel.add(new Label("Gender:"));
						 if(curUser.gender!=' ')
							 if(curUser.gender=='M')
								 gender.setSelectedIndex(0);
							 else
								 gender.setSelectedIndex(1);
						 mainPanel.add(gender);
						 mainPanel.add(new Label("Email:"));
						 email.setText(curUser.email);
						 mainPanel.add(email);
						 mainPanel.add(new Label("Birthdate:"));
						 DateTimeFormat df=DateTimeFormat.getFormat("MMMM dd yyyy");
						 if(curUser.dob!=null){
							 dob.setValue(curUser.dob);
						 }
						 dob.setFormat(new DateBox.DefaultFormat(df));
						 mainPanel.add(dob);
						 mainPanel.add(new Label("Address:"));
							 if(curUser.address!=null)
								 address.setText(curUser.address);
							 mainPanel.add(address);
							 mainPanel.add(new Label("Academic Institution:"));
						 if(curUser.school!=null)
							 school.setText(curUser.school);
						 mainPanel.add(school);

						 mainPanel.add(new Label("Interests:"));
						 if(curUser.interests!=null){
							 int b=curUser.interests.length()-1;
							 if(b<0)
								 b=0;
							 interests.setText(curUser.interests.substring(0,b));
						 }
						 mainPanel.add(interests);
						 
						 if(utype.equals("P")){
							 mainPanel.add(new Label("Room Number:"));
							 if(curUser.roomNumber!=0)
								 rmNumber.setText(Integer.toString(curUser.roomNumber));
							 mainPanel.add(rmNumber);
								 
							 mainPanel.add(new Label("Research Areas:"));
							 if(curUser.researchArea!=null)
								 research.setText(curUser.researchArea);
							 mainPanel.add(research);
							 
						 }
						 
						 else{
							 mainPanel.add(new Label("Advisor:"));
						getAdvisors();
						if(curUser.advises!=0)
							for(int a=0;a<faculty.getItemCount();a++){
								if(faculty.getValue(a)==Integer.toString(curUser.advises))
									faculty.setItemSelected(a, true);
							}
						mainPanel.add(faculty);
						mainPanel.add(new Label("#Years Advised:"));
						 if(curUser.yearsAdvised!=0) 
							 yearsAd.setText(Integer.toString(curUser.yearsAdvised));
						 mainPanel.add(yearsAd);
						 mainPanel.add(new Label("Major:"));
						 if(curUser.major!=null) 
							 major.setText(curUser.major);
						 mainPanel.add(major);
						 mainPanel.add(new Label("GPA:"));
						 if(curUser.GPA!=0) {
	                		   String formatted = NumberFormat.getFormat("0.00").format(curUser.GPA);
							 gpa.setText(formatted);
						 }
						 mainPanel.add(gpa);
						 mainPanel.add(new Label("Year:"));
						 if(curUser.year!=0) 
							 year.setText(Integer.toString(curUser.year));
						 mainPanel.add(year);
						
						}
					
					}
	                  public void onFailure(Throwable caught) {
	                	  errorLabel.setText("DB error");
	                  }            
	                  
	          });
				String  html= "<td colspan='2' style='color:red;' id='errorLabelContainer'></td>"+
					      "</tr>"+
					      "<tr>"+
					        "<td colspan='2' style='color:green;' id='notificationContainer'></td>"+
					      "</tr>";
			mainPanel.add(new HTML(html));
			mainPanel.addStyleName("paddedHorizontalbottom");
			editForm.add(mainPanel);
				contentPanel.add(editForm);
				contentPanel.add(addPanel);
				outer.add(contentPanel);
		  }
public boolean updateUser(final int id, User u,final String type,final String username)
				  throws IllegalArgumentException {

			  final boolean success=false;
			  
			  notifyLabel.setText("Sending Data....");  
		  pService.updateUser(id,u,type,new AsyncCallback<Boolean>() {
			    public void onSuccess(Boolean result) {
			    	  //resetFields();
			    	  //RootPanel.get("notificationContainer").clear();
			    	  Window.alert("Details have been successfully updated");
			    	  FlowControl.go(new UserProfile(id,type,0, username,1));
			    	  //boolean success=result;
			  		 // notifyLabel.setText("User has been successfully saved");
			      }
			      
			      public void onFailure(Throwable caught) {
			    	  //RootPanel.get("notificationContainer").clear();
			  		  errorLabel.setText("There was an error saving to database");
			  		  //RootPanel.get("notificationContainer").add(errorLabel);
			      }
			     
			    
			
			  });  
		  return success;  
	}
	}
